package me.zhengjie.modules.test.service.impl;

import me.zhengjie.modules.test.domain.JgxTest;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.test.repository.JgxTestRepository;
import me.zhengjie.modules.test.service.JgxTestService;
import me.zhengjie.modules.test.service.dto.JgxTestDTO;
import me.zhengjie.modules.test.service.dto.JgxTestQueryCriteria;
import me.zhengjie.modules.test.service.mapper.JgxTestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author jie
* @date 2019-06-25
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JgxTestServiceImpl implements JgxTestService {

    @Autowired
    private JgxTestRepository jgxTestRepository;

    @Autowired
    private JgxTestMapper jgxTestMapper;

    @Override
    public Object queryAll(JgxTestQueryCriteria criteria, Pageable pageable){
        Page<JgxTest> page = jgxTestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(jgxTestMapper::toDto));
    }

    @Override
    public Object queryAll(JgxTestQueryCriteria criteria){
        return jgxTestMapper.toDto(jgxTestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public JgxTestDTO findById(Integer id) {
        Optional<JgxTest> jgxTest = jgxTestRepository.findById(id);
        ValidationUtil.isNull(jgxTest,"JgxTest","id",id);
        return jgxTestMapper.toDto(jgxTest.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JgxTestDTO create(JgxTest resources) {
        return jgxTestMapper.toDto(jgxTestRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(JgxTest resources) {
        Optional<JgxTest> optionalJgxTest = jgxTestRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalJgxTest,"JgxTest","id",resources.getId());

        JgxTest jgxTest = optionalJgxTest.get();
        // 此处需自己修改
        resources.setId(jgxTest.getId());
        jgxTestRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        jgxTestRepository.deleteById(id);
    }
}